import css from '../css/index.css';
var web_url = 'http://114.215.223.123/WebNews/public/index.php/index/';
var imgUrlicon = require('../images/websiteicon.png');
var defaultNavicon = require('../images/defaultNavicon.png');
var global_haveEr = true;//标记为是否有二级菜单
var msgtime = 1800;
// 点击一级
$(function(){
    //加载左边导航
    ajax_leftNav_fn();

    //点击一级
    var global_editNavElenmentText = null;//左部编辑导航text
    var global_editNavElenmentInput = null;//左部编辑导航input
    $('#left_nav').on('click','.left-yi',(e)=>{
        var self = $(e.currentTarget);
        self.find('.yi-text').css('color','#22a7f0');
        self.parent().siblings().find('.left-yi .yi-text').css('color','#fff')
        $('.left-erul').each((i,v)=>{//不是当前的二级类型隐藏
            if($(v)[0] != self.siblings('.left-erul')[0]){
                $(v).slideUp();
            }
        })
        //显示隐藏二级菜单
        self.siblings('.left-erul').slideToggle();
        //要改变的字段
        global_editNavElenmentText = self.find('.yi-text');
        //编辑的input
        global_editNavElenmentInput = self.find('input');
        global_haveEr = true;
        if(!self.next().attr('class')){//如果没有二级就请求列表
            global_selectNavId = self.attr('data-navid');
            if(global_selectNavId == 'recommend'){//如果是推荐分类
                $('#form_div').slideUp()//隐藏添加操作
            }else{
                $('#form_div').slideDown()
            }
            clear_fn();
            ajax_website_list_fn();
            $('.system-nav-text').text(global_editNavElenmentText.text())
            global_haveEr = false;
        }
    })

     // 点击左部份的头部操作类型（增删改）
     $('#nav_operation').on('click','img',(e2)=>{
        var selfimg = $(e2.currentTarget);
        var alt = selfimg.prop('alt');
        if(alt == '添加'){//添加导航
            if(!global_haveEr){
                layer.msg('很遗憾！此导航不能添加子级',{
                    time:msgtime,
                    icon:5
                })
                return false
            }
            var title,paerntId,id;
            if(!global_editNavElenmentText){
                title = '添加(新)类型'
                paerntId = 0;
            }else{
                if(global_editNavElenmentText.parent().hasClass('left-yi')){//一级
                    var bt = global_editNavElenmentText.text();
                    title = `添加(${bt})二级标题`;
                    paerntId = global_editNavElenmentText.parent().attr('data-navId');
                }else if(global_editNavElenmentText.parent().hasClass('left-erContent')){
                    var yi = global_editNavElenmentText.parents('.left-erul').prev();
                    paerntId = yi.attr('data-navid');
                    var bt = yi.find('.yi-text').text();
                    title = `添加(${bt})二级标题`;
                }
                
            }
            var layerindex = layer.open({
                type:1,
                title:title,
                // closeBtn:0,
                area:'400px',
                shadeClose:true,
                content:$('#addLeftNav_input'),
                end:function(){
                    $('#addLeftNav_input').css('display','none')
                }
            })
            if(paerntId != 0){
                //如果是添加二级隐藏弹框中的单选
                $('.radio-class').css('display','none').next().css('display','none')
            }else{//新添加导航
                $('.radio-class').css('display','block').next().css('display','block')
                
            }
            clearTk_fn()
            $('#center_input').data({paerntId,layerindex});
            $('#center_input').focus();
            show_hide_upicon('hide','#up_imag2')

        }else if(alt == '删除'){
            if(!global_editNavElenmentInput || !global_editNavElenmentText){
                layer.msg('请点击删除对象',{
                    time:msgtime,
                    icon:0
                })
                return false;
            }
            var parent_ = global_editNavElenmentText.parent();
            var parent_id = parent_.attr('data-navparentid');
            var msgT = '';
            var id  = global_editNavElenmentText.parent().attr('data-navid');
            if(parent_id == 0){//删除的一级
                msgT = "一级类别";
            }else{
                if(parent_.parent().siblings('li').length == 0){//如果删除的最后一个二级类型
                    msgT =  '(这是最后一个二级类型,删除后一级类型也将同时删除)';
                    id  = global_editNavElenmentText.parents('.left-erul').prev().attr('data-navid');
                }else{
                    msgT = "二级类别";
                }
            }
            layer.confirm(`确定要删除这个<span style="color:red">${global_editNavElenmentText.text()}</span>${msgT}`,{
                btn: ['确定', '取消']
            },function(i){
                // var id = global_editNavElenmentText.parents('li')[0].remove();//删除对应的li
                ajax_fn(web_url+'navigation/nav_del',{id},function(data){
                    if(data.status == 'success'){
                        ajax_leftNav_fn();
                        global_editNavElenmentText = null;
                    }else{
                        layer.msg(data.message,{
                            time:msgtime,
                            icon:0
                        })
                    }
                })
                layer.close(i)
            })
        }else if(alt == '编辑'){
            if(!global_editNavElenmentInput && !global_editNavElenmentText){
                layer.msg('请点击编辑对象',{
                    time:msgtime,
                    icon:0
                })
                return;
            }
            global_editNavElenmentInput.css('display','inline-block').val(global_editNavElenmentText.text()).focus();
            global_editNavElenmentText.css('display','none');
            global_editNavElenmentInput.click(function(e3){
                e3.stopPropagation()
            }).blur(function(){
                global_editNavElenmentText.css('display','inline-block');
                global_editNavElenmentInput.css('display','none');
            }).keydown(function(keye){
                if(keye.keyCode == 13){//回车保存修改内容
                    pass_val()
                }
            })
            //判断输入的值是否为空修改函数
            const pass_val = ()=>{
                if($.trim(global_editNavElenmentInput.val()) == ''){
                    layer.msg('哇哦！修改名称不能为空',{
                        time:msgtime,
                        icon:5
                    })
                    global_editNavElenmentInput.focus()
                }else{
                    var data = {
                        parent_id:global_editNavElenmentInput.parent().attr('data-navParentId'),
                        id:global_editNavElenmentInput.parent().attr('data-navid'),
                        name:global_editNavElenmentInput.val()
                    }
                    ajax_fn(web_url+'navigation/nav_save',data,function(data){
                        if(data.status = 'success'){
                            layer.msg(data.message,{
                                time:msgtime,
                                icon:6
                            })
                            global_editNavElenmentText.css('display','inline-block').text(global_editNavElenmentInput.val());
                            global_editNavElenmentInput.css('display','none');
                        }else{
                            layer.msg(data.message,{
                                time:msgtime,
                                icon:5
                            })
                        }
                    })
                }
            }
        }
    })

    //点击新增一级或者二级单选
    var global_selectAddNewNav = "newAddyi";//标记新增加类型一级还是二级(默认选中一级)
    $('#addLeftNav_input').on('click','.radioEveryone',(e)=>{
        var self = $(e.currentTarget);
        var type = self.attr('data-type');
        var i = self.find('i');
        i.removeClass('icon-danxuan').addClass('icon-danxuan1').css('color','#64ba7c');
        i.parent().siblings().find('i').removeClass('icon-danxuan1').addClass('icon-danxuan').css('color','#8a8a8a');
        if(type == 'er'){
            global_selectAddNewNav = "newAdder";
            var inputs = `<div class="layui-form-item">
                            <div class="layui-input-inline">
                                <input type="text" required placeholder="请输入二级菜单标题" class="layui-input">
                            </div>
                            <div class="layui-form-mid layui-word-aux add-erinput">+</div>
                        </div>`
            $('#tker_div').append(inputs);
            $('#tker_div').slideDown();
        }else{
            global_selectAddNewNav = "newAddyi";
            $('#tker_div').slideUp()
        }
    })

    //点击添加二级input
    $('#tker_div').click((e)=>{
        var self = $(e.target);
        if(self.hasClass('add-erinput')){//点击的是加号
            var inputs = `<div class="layui-form-item">
                            <div class="layui-input-inline">
                                <input type="text" required placeholder="请输入二级菜单标题" class="layui-input">
                            </div>
                            <div class="layui-form-mid layui-word-aux delete-erinput">-</div>
                            <div class="layui-form-mid layui-word-aux add-erinput">+</div>
                        </div>`
            self.parent().after(inputs)
        }else if(self.hasClass('delete-erinput')){
            self.parent().remove()
        }
    })

    // 弹框中的所有input回车事件
    $('#addLeftNav_input').on('keydown','input',(e)=>{
        var  key = e.keyCode;
        if(key == 13){
            var data ={};
            var yiElent = $('#center_input');
            var parent_id = yiElent.data('paerntId');//添加导航的父级id
            var layerindex = yiElent.data('layerindex');//对应的layer
            var yiname = $.trim(yiElent.val());
            if(yiname == ''){
                layer.msg('一级名称不能为空',{
                    time:msgtime,
                    icon:5
                })
            }else{
                var imgurl = $('#up_imag2').find('img').attr('src');
                if(global_selectAddNewNav == 'newAddyi'){
                    data ={
                        photos:imgurl,
                        parent_id,
                        name:yiname
                    }
                }else if(global_selectAddNewNav == 'newAdder'){//如果添加的新导航有二级菜单
                    var erArrayName = [];//二级名称
                    var erinputs = $('#tker_div input');
                    erinputs.each((i,v)=>{
                        var val = $.trim($(v).val());
                        if(val != ''){
                            erArrayName.push(val)
                        }
                    })
                    if(erArrayName.length == 0){
                        layer.msg('至少要添加一个二级导航',{
                            time:msgtime,
                            icon:5
                        })
                        return false                
                    }else{
                        data ={
                            photos:imgurl,
                            parent_id,
                            name:yiname,
                            name1:erArrayName.join(',')
                        }
                    }
                }
                
                ajax_fn(web_url+'navigation/nav_save',data,function(data){
                    if(data.status = 'success'){
                        ajax_leftNav_fn();
                        layer.msg(data.message,{
                            time:msgtime,
                            icon:6
                        })
                        layer.close(layerindex);
                        $('#addLeftNav_input').css('display','none')
                    }else{
                        layer.msg(data.message,{
                            time:msgtime,
                            icon:0
                        })
                    }
                })

            }
        }
    })


    //点击二级
    $('#left_nav').on('click','.left-erul li',(e)=>{
        var self = $(e.currentTarget).find('.left-erContent');
        self.find('.er-text').css('color','#22a7f0');
        self.parent().siblings().find('.er-text').css('color','#fff');//同级的二级菜单
        self.parents('.left-erul').parent().siblings().find('.er-text').css('color','#fff');//父级的二级菜单
        global_editNavElenmentText = self.find('.er-text');
        global_editNavElenmentInput = self.find('input');
        global_selectNavId = self.attr('data-navid');
        ajax_website_list_fn();
        clear_fn();
        $('#form_div').slideDown();
        $('.system-nav-text').text(global_editNavElenmentText.text())
    })
    

    //选择图片
    $('.up-add').click(function(){
        $(this).siblings('input').click()
    })
    //改变选择图片
    $('.fileinput').change(function(){
        var parentid = $(this).parent().attr('id');
        look_img(this,'#'+parentid);
        // var path = up_file.value;
        // var objUrl = getObjectURL(this.files[0]);
        // console.log(this.files)
        // if(objUrl){
        //     $('#website_icon').attr("src",objUrl);
        //     $('#website_icon').attr("data-name",this.files[0].name);
        //     show_hide_upicon('show');
        // }
    })
    //删除图标
    $('.delete-upicon').click(function(){
        var parentid = $(this).parent().attr('id');
        show_hide_upicon('hide','#'+parentid);
    })
    //data:显示图标判断参数
    const show_hide_upicon = function(data,imgobj){
        if(data!='show'){
            $(imgobj).find('input').val('');
            $(imgobj).find('img').attr('src','');
        } 
        $(imgobj).find('.up-add').css('display',data == 'show'?'none':'block');//加号
        $(imgobj).find('.delete-upicon').css('display',data == 'show'?'block':'none');//删除
        $(imgobj).find('img').css('display',data == 'show'?'block':'none');//图片
    }
    //预览图片
    const look_img =(file,imgobj)=>{
        if(!file.files || !file.files[0]){
            return;
        }
         var reader = new FileReader();
         reader.onload = function(evt){
            $(imgobj).find('img').attr("src",evt.target.result);
        }
        reader.readAsDataURL(file.files[0]);
        show_hide_upicon('show',imgobj);
    }

    //获取图片路径
    const getObjectURL = (filesurl)=>{
        var url = null;
        if(window.createObjectURL != undefined){
            url = window.createObjectURL(filesurl);//basic
        }else if(window.URL != undefined){
            url = window.URL.createObjectURL(filesurl);
        }else if(window.webkitURL != undefined){
            url = window.webkitURL.createObjectURL(filesurl);
        }
        return url;
    }
    /*中间内容部分添加修改网址*/
    $('#edit_website').click((e)=>{
        var inputN = $('#websiteName_input');
        var inputU = $('#websiteUrl_input');  
        if($.trim(inputN.val()) == ''){
            layer.msg('请输入网址名称',{
                time:msgtime,
                icon:5
            })
        }else if($.trim(inputU.val()) == ''){
            layer.msg('请输入网址地址',{
                time:msgtime,
                icon:5
            })
        }else{
            var data = false;
            if(global_websiteId){//是否是修改地址
                data ={
                    id:global_websiteId,
                    dict_id:global_selectNavId,
                    name:inputN.val(),
                    url:inputU.val()
                }
            }else{//如果没有id，就是新添加网址
                var uls = $('#website_ul');
                var pass_add = true;
                uls.find('.move-content').each((i,v)=>{//判断是否重复添加
                    var selfu = $(v).attr('data-websiteUrl');
                    if(selfu == inputU.val()){
                        pass_add = false;
                        return false
                    }
                })
                if(pass_add){
                    data ={
                        dict_id:global_selectNavId,
                        name:inputN.val(),
                        url:inputU.val()
                    }
                }else{
                    data = false;
                    layer.msg('网址已存在',{
                        time:msgtime,
                        icon:5
                    })
                }
            }
            if(data){
                var urlicon = $('#up_img').find('img').attr('src');
                data.photos = urlicon;
                ajax_fn(web_url+'Url/url_save',data,function(data){
                    if(data.status == 'success'){
                        ajax_website_list_fn();
                        show_hide_upicon('hide','#up_img');
                    }else{
                        layer.msg(data.message,{
                            time:msgtime,
                            icon:6
                        })
                    }
                })
            }
            
            clear_fn();//重置input
        }
    })

    //重置
    $('#reset_website').click((e)=>{
        clear_fn()
    })
    //点击编辑删除网址
    var global_websiteId = null;//存储点击编辑后的网址id
    $('#website_ul').click((e)=>{
        var self = $(e.target);
        var selfclassName = self.attr('class');
        global_websiteId = self.parent().attr('data-websiteId');//对应id
        var websiteUrl = self.parent().attr('data-websiteUrl');
        var recommend = self.parent().attr('data-recommend');
        if(selfclassName == 'website-name'){
            window.open(websiteUrl)
        }else if(selfclassName.indexOf('sign') != -1){//标记
            if(recommend == 0){
                self.css('color','#00c853')
            }else if(recommend == 1){
                self.css('color','#8a8a8a')
            }
            var data = {
                recommend,
                id:global_websiteId
            }
            ajax_fn(web_url+'Url/is_recommend',data,(data)=>{})
        }else if(selfclassName == 'edit'){//编辑网址
            var websiteName = self.parent().attr('data-websiteName');
            var iconurl = self.parent().attr('data-iconurl');
            $('#websiteName_input').val(websiteName);
            $('#websiteUrl_input').val(websiteUrl);
            $('#up_img').find('img').attr('src',iconurl)
            $('#edit_website').text('修改');
            show_hide_upicon('show','#up_img');
        }else if(selfclassName == 'delete'){//删除网址
            self.parents('li').remove();
            if(global_selectNavId == 'recommend'){//如果删除的推荐网址就用另一个接口
                var data = {
                    recommend,
                    id:global_websiteId
                }
                ajax_fn(web_url+'Url/is_recommend',data,(data)=>{})
            }else{
                ajax_fn(web_url+'Url/url_del',{id:global_websiteId},function(){})
            }
        }
    })
    //拖动排序
    var startnode = null;//开始拖动元素
    $('#website_div').on('dragstart','li',(e)=>{
        startnode = $(e.currentTarget);
    }).on('dragover','li',(e)=>{
        e.preventDefault();
    }).on('drop','li',(e)=>{
        e.preventDefault();
        var endnode = $(e.currentTarget);
        var endh = endnode.html();
        var starId = startnode.find('.move-content').attr('data-websiteid'); 
        var endId = endnode.find('.move-content').attr('data-websiteid');
        var data = {
            dict_id:global_selectNavId,
            id:`${starId},${endId}`
        }
        endnode.html(startnode.html())
        startnode.html(endh);
        if(starId != endId){
            ajax_fn(web_url+'Url/url_order',data,function(data){
            
            })
        }
    })

    //点击重置选中
    $('.body-left').click((e)=>{
        if($(e.target).hasClass('body-left')){
            global_editNavElenmentText = null;
            global_haveEr = true;
            clearDrag_fn()
        }
    })

    //左部拖动排序
    const aa = function(){
        alert('鼠标离开')
    }
    $('#left_nav').on('dragstart','li.draggable-yi',(e)=>{
        startnode = $(e.currentTarget);
        
    }).on('dragover','li.draggable-yi:not(:last-child)',(e)=>{
        e.preventDefault();
        var lis = $('#left_nav>li');
        $(e.currentTarget).siblings().css('boxShadow','none');
        $(e.currentTarget).css('boxShadow','0px 2px 1px #22a7f0');
    }).on('drop','li.draggable-yi',(e)=>{
        var endnode = $(e.currentTarget);
        clearDrag_fn();
        if(startnode.hasClass('draggable-er')){//拖动结束如果二级放到一级中会不成功
            layer.msg('抱歉只能在同级中改变顺序',{
                time:msgtime,
                icon:5
            })
            return false;
        }     
        var endh = endnode.html();
        var starId = startnode.find('.left-yi').attr('data-navid'); 
        var endId = endnode.find('.left-yi').attr('data-navid');
        var data = {
            id:`${starId},${endId}`
        }
        endnode.html(startnode.html())
        startnode.html(endh);
        if(starId != endId){
            ajax_fn(web_url+'navigation/nav_order',data,function(data){
            
            })
        }
        e.preventDefault();
    })

    //拖动排序二级
    $('#left_nav').on('dragstart','li.draggable-er',(e)=>{
        startnode = $(e.currentTarget);
        e.stopPropagation()        
    }).on('dragover','li.draggable-er',(e)=>{
        var self = $(e.currentTarget);
        if(startnode.hasClass('draggable-yi')){//如果拖动的是一级菜单
            return false;
        }
        self.css('boxShadow','1px 1px 1px #22a7f0').siblings().css('boxShadow','none');
        e.stopPropagation()
        e.preventDefault();
    }).on('drop','li.draggable-er',(e)=>{
        var self = $(e.currentTarget);
        var endHtml = self.html();
        clearDrag_fn();
        if(startnode.hasClass('draggable-yi')){
            layer.msg('抱歉! 不能越级操作',{
                time:msgtime,
                icon:5
            })
            return false
        }
        var starId = startnode.find('.left-erContent').attr('data-navid'); 
        var endId = self.find('.left-erContent').attr('data-navid');

        self.html(startnode.html());
        startnode.html(endHtml);
        var data = {
            id:`${starId},${endId}`
        }
        if(starId != endId){//改变了顺序才请求
            ajax_fn(web_url+'navigation/nav_order',data,function(data){
            
            })
        }

        e.stopPropagation();
        e.preventDefault();
    })


    //重置拖动样式
    const clearDrag_fn = ()=>{
        $('li.draggable-yi').css('boxShadow','none');
        $('li.draggable-er').css('boxShadow','none');
    }

    //重置添加修改操作
    const clear_fn = ()=>{
        $('#websiteName_input').val('');
        $('#websiteUrl_input').val('');
        $('#edit_website').text('添加');
        global_websiteId = '';
        show_hide_upicon('hide','#up_img')
    }

    //重置弹框操作
    const clearTk_fn = ()=>{
       $('.radioEveryone:first').find('i').removeClass('icon-danxuan').addClass('icon-danxuan1').css('color','rgb(100, 186, 124)');//选中一级
       $('.radioEveryone:gt(0)').find('i').removeClass('icon-danxuan1').addClass('icon-danxuan').css('color','#8a8a8a');//选中一级
       $('.tk-erdiv').css('display','none');
       global_selectAddNewNav = "newAddyi";
       $('#center_input').val('');
       $('#tker_div').html('<p class="title">二级标题</p>')
    }
})



var global_selectNavId;//用于请求网址列表的id;
//左部导航请求
const ajax_leftNav_fn = ()=>{
    ajax_fn(web_url+'navigation/nav_list',{},function(data){
        if(data.status == 'success'){
            var lis = ``;
            $.each(data.result,(i,v)=>{
                var yi_color = '';
                var display = "display:none";
                if(i == 0){
                    var display = "display:block";
                    yi_color = '#22a7f0'
                    global_selectNavId = v.id;
                    $('.system-nav-text').text(v.name);
                }
                if(v.id == 'recommend'){//如果是推荐的网址不能排序
                    lis += `<li>`
                }else{
                    lis += `<li draggable="true" class="draggable-yi">`
                }
                var navicon = v.dict_photo?v.dict_photo:defaultNavicon;
                lis += `<div class="left-yi" data-navId="${v.id}" data-navParentId="${v.parent_id}">
                                <img src="${navicon}" />
                                <span class="yi-text" style="color:${yi_color}">${v.name}</span>
                                <input type="text" style="width:85px;display:none">`
                                if(v.children.length != 0){
                                    
                                    lis += `<i class="yi-iconR iconfont icon-xia"></i>`;
                                    lis += `</div>
                                            <ul class="left-erul" style="${display}">`
                                               $.each(v.children,(i2,v2)=>{
                                                var er_color = '';
                                                if(i2 == 0 && i == 0){
                                                    $('.system-nav-text').text(v2.name)
                                                    global_selectNavId = v2.id;
                                                    er_color = '#22a7f0'
                                                }
                                                lis += `<li draggable="true" class="draggable-er">
                                                            <div class="left-erContent" data-navId = "${v2.id}" data-navParentId="${v2.parent_id}">
                                                                <span class="er-text" style="color:${er_color}">${v2.name}</span>
                                                                <input style="width:130px;display:none" type="text">
                                                            </div>
                                                    </li>`
                                               })
                                            lis += `</ul>
                                        </li>`
                                }else{
                                    lis += `</div></li>`
                                }
            })
            $('#left_nav').html(lis);
            ajax_website_list_fn()
        }
    })
}

//右部对应的网址列表
const ajax_website_list_fn = ()=>{
    ajax_fn(web_url+'Url/url_list',{dict_id:global_selectNavId},function(data){
        if(data.status == 'success'){
            var lis ='';
            $.each(data.result,(i,v)=>{
                var imageurl = v.cfg_photo?v.cfg_photo:imgUrlicon;
                lis += `<li draggable="true">
                            <div class="move-content" data-recommend = "${v.recommend}" data-websiteId = "${v.id}" data-iconUrl = "${imageurl}" data-websiteUrl = "${v.url}" data-websiteName ="${v.name}">
                                <img src="${imageurl}" />
                                <span class="website-name">${v.name}</span>`
                                if(global_selectNavId == 'recommend'){

                                }else{
                                    if(v.recommend == 1){
                                        lis += `<i style="color:#00c853" class="sign iconfont icon-directmailyoujiantuisong"></i>`
                                    }else{
                                        lis += `<i class="sign iconfont icon-directmailyoujiantuisong"></i>`
                                    }
                                    lis += `<i class="edit"></i>`;
                                }
                                lis += `<i class="delete"></i>
                            </div>
                        </li>`
            })
            $('#website_ul').html(lis)
        }else{
            $('#website_ul').html('')
            layer.msg(data.message,{
                time:msgtime,
                icon:5
            })
        }
    })
}
//ajax请求
const ajax_fn = (url,data,success,error=(a,b,c)=>{layer.msg(b)})=>{
    $.ajax({
        url:url,
        data:data,
        dataType:'json',
        type:"post",
        success:function(data){
            success(data)
        },error:function(er,type,hr){
            error()
        }
    })
}